<template>
  <div class="login">
    <h1>后台管理系统</h1>
    <el-form
      :model="loginForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="small"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          placeholder="请输入用户名"
          v-model="loginForm.userName"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          placeholder="请输入密码"
          v-model="loginForm.password"
          @keyup.enter="handleOk"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div class="code-input">
          <el-input
            @keyup.enter="handleOk"
            placeholder="请输入验证码"
            v-model="loginForm.code"
          ></el-input>
          <img @click="getCode" :src="imgUrl" alt="加载失败" />
        </div>
      </el-form-item>
      <el-form-item class="itemEnd">
        <el-button type="primary" :loading="isLoad" @click="handleOk"
          >立即登录</el-button
        >
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted, h } from 'vue'
import { loginRules } from '@/views/login/config/login-rules'
import { ElForm, ElNotification } from 'element-plus'
import { $login } from '@/service/common'
import { twtRequest } from '@/service'
import { transformArrayBufferToBase64, isToday } from '@/assets/common'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'

export default defineComponent({
  name: 'Login',
  setup() {
    const store = useStore()
    const loginForm = reactive({
      userName: 'admin',
      password: '2wsx!QAZ',
      code: '',
      captchaCode: '',
      requestId: ''
    })
    const imgUrl = ref('')
    const isLoad = ref(false)
    const router = useRouter()
    const rules = loginRules
    const ruleForm = ref<InstanceType<typeof ElForm>>()
    const handleOk = () => {
      ruleForm.value?.validate((res) => {
        if (!res) return
        isLoad.value = true
        const isLoginObj = sessionStorage.getItem('loginId')
        let loginObj
        if (isLoginObj) loginObj = JSON.parse(isLoginObj)
        console.log(loginObj)
        loginForm.requestId = loginObj.requestid
        loginForm.captchaCode = loginObj.captchacode
        $login
          .loginOk(loginForm)
          .then((res) => {
            if (res.code !== 200)
              return ElNotification({
                title: '错误信息',
                message: h('h3', { style: 'color: red' }, res.message)
              })
            localStorage.setItem('token', res.data.access_token)
            store.dispatch('login/getAgentCodeArr')
            router.push('/')
            ElNotification({
              title: '登录成功',
              message: h('h3', { style: 'color: red' }, isToday())
            })
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {
            getCode()
            isLoad.value = false
          })
      })
    }

    // 获取验证码
    const getCode = () => {
      twtRequest
        .get({
          url: '/asm/getCaptcha',
          responseType: 'arraybuffer'
        })
        .then((res) => {
          imgUrl.value =
            'data:image/jpeg;base64,' + transformArrayBufferToBase64(res)
        })
        .catch(() => console.log('获取验证码失败'))
    }
    onMounted(() => {
      getCode()
    })
    return {
      loginForm,
      ruleForm,
      rules,
      isLoad,
      imgUrl,
      getCode,
      handleOk
    }
  }
})
</script>

<style scoped lang="less">
.login {
  h1 {
    text-align: center;
    margin: 15px;
    font-size: 30px;
    font-weight: 600;
  }
  width: 500px;
  box-sizing: border-box;
  padding: 10px 15px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  .itemEnd {
    /deep/.el-form-item__content {
      display: flex;
      justify-content: flex-end;
    }
  }
  .code-input {
    display: flex;
    /deep/.el-input {
      margin-right: 20px;
      flex: 2;
    }
    img {
      flex: 1;
      height: 32px;
      cursor: pointer;
    }
  }
}
</style>
